package com.dahua.ui;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dahua.R;
import com.dahua.ui.base.MyBaseFragmentActivity;
import com.dahua.ui.main.UpdateDialog;
import com.dahua.ui.user.RegisterAct;
import com.dahua.ui.views.LoadingDialog;
import com.dahua.utils.HttpUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * 开屏页
 */
public class SplashActivity extends MyBaseFragmentActivity {
    private RelativeLayout rootLayout;
    private TextView versionText;
    private static final int SEND_LOGIN_REQUEST = 0x1111;

    private static final int sleepTime = 2000;

    public Dialog loadingDialog;

    private ProgressDialog pBar;

    private TextView title;
    private TextView conntent;
    private TextView negative;
    private TextView positive;
    private View negative_view;

    public static String appName = "Partner";

    @Override
    public void onCreate(Bundle arg0) {
        setContentView(R.layout.splash);
//        Window window = getWindow();
//        //设置透明状态栏,这样才能让 ContentView 向上
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//        //设置状态栏颜色
////        window.setStatusBarColor(statusColor);
//        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
//        View mChildView = mContentView.getChildAt(0);
//        if (mChildView != null) {
//            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
//            ViewCompat.setFitsSystemWindows(mChildView, false);
//        }
        super.onCreate(arg0);
        update();

        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            window.getDecorView().setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.title_background));
        }
//        Message msg = new Message();
//            msg.what = 1;
//
//        handler.sendMessageDelayed(msg, 1000);
    }

    //版本更新接口
    public void update() {
//        showLoadingDialog();
        HttpUtils.getInstance().update(handler, SplashActivity.this);
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                    i.putExtra("url", "views/product/category.html");
                    startActivity(i);
                    finish();
                    break;
                case 2:
                    Message msg1 = new Message();
                    msg1.what = 1;

                    handler.sendMessageDelayed(msg1, 1000);
                    break;
                case 10:
//                    UpdateVersionBean data = new UpdateVersionBean();
//                    JSONObject jo0 = (JSONObject)msg.obj;
//                    JSONObject jo1 = jo0.optJSONObject("object");
//                    data.setANDROID_DOWNLOAD_URL(jo1.optString("ANDROID_DOWNLOAD_URL"));
//                    data.setANDROID_UPDATE_DESC(jo1.optString("ANDROID_UPDATE_DESC"));
//                    data.setANDROID_VERSION(jo1.optString("ANDROID_VERSION"));

                    SharedPreferences userSettings = getSharedPreferences("versioninfo", 0);
                    final String new_version_code = userSettings.getString("version", "");
                    final String desc = userSettings.getString("desc", "");
                    final String uri = userSettings.getString("uri", "");

                    //获取包管理器
                    PackageManager pm = getPackageManager();
                    PackageInfo packageInfo = null;
                    String version_code = "";
                    try {
                        packageInfo = pm.getPackageInfo(getPackageName(), 0);
                        version_code = packageInfo.versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    String old_version_code = String.valueOf(version_code);

                    float serverVersion = 0f;//服务器版本号
                    try {
                        serverVersion = Float.valueOf(new_version_code);
                    } catch (Exception e) {
                        serverVersion = 0f;
                    }

                    float localVersion = 0f;//当前应用版本号
                    try {
                        localVersion = Float.valueOf(version_code);
                    } catch (Exception e) {
                        localVersion = 0f;
                    }

                    if (serverVersion > localVersion) {//如果服务器版本号大于当前应用版本号，则弹更新提示
                        showUpdateDialog(new_version_code, desc, uri, false);
                    } else {
                        Message msg2 = new Message();
                        msg2.what = 1;

                        handler.sendMessageDelayed(msg2, 1000);
                    }

//                    if (new_version_code != null && !new_version_code.equals(old_version_code)&&!"0".equals(new_version_code)){
//                        showUpdateDialog(new_version_code,desc, uri, false);
//                    }else{
//                        Message msg2 = new Message();
//                        msg2.what = 1;
//
//                        handler.sendMessageDelayed(msg2, 1000);
//                    }
                    userSettings.edit().clear();

                    break;


                default:
                    break;
            }
        }
    };

    public void showUpdateDialog(String newVersion, String content, final String url, Boolean mustUpdate) {

        if (content != null && !content.equals("")) {
            UpdateDialog dialog = UpdateDialog.newInstance(mustUpdate, "Version Update",
                    "" + content,
                    "Cancel", "OK", new UpdateDialog.setOnHintListener() {
                        @Override
                        public void onNegative() {
                            Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                            i.putExtra("url", "views/product/category.html");
                            startActivity(i);
                            finish();
                        }

                        @Override
                        public void onPositive() {
                            showProgressBar(url);// 更新当前版本
                        }
                    });
            dialog.show(getSupportFragmentManager(), "");

        }
    }

    protected void showProgressBar(String url) {
        pBar = new ProgressDialog(this);
        pBar.setTitle("Download");
        pBar.setCanceledOnTouchOutside(false);
        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        downAppFile(url);
    }

    protected void downAppFile(final String url) {
        pBar.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    Log.i("DownTag", "" + (int) length);
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is == null) {
                        throw new RuntimeException("isStream is null");
                    }
                    File file = new File(
                            Environment.getExternalStorageDirectory(), appName);
                    fileOutputStream = new FileOutputStream(file);
                    byte[] buf = new byte[64];
                    long total = 0;
                    int ch = -1;
                    do {
                        ch = is.read(buf);
                        if (ch <= 0)
                            break;
                        fileOutputStream.write(buf, 0, ch);
                        total = total + buf.length;
                        Log.i("DownTag", "" + (int) (100 * total / length));
                        Message message = Message.obtain();
                        message.arg1 = (int) (100 * total / length);
                        progressHandler.sendMessage(message);

                    } while (true);
                    is.close();
                    fileOutputStream.close();

                    String command = "chmod " + "666" + " "
                            + Environment.getExternalStorageDirectory() + "/"
                            + appName;
                    Runtime runtime = Runtime.getRuntime();
                    runtime.exec(command);
//                    haveDownLoad();
                    installNewApk();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private Handler progressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!Thread.currentThread().isInterrupted()) {
                pBar.setProgress(msg.arg1);
            }
            super.handleMessage(msg);
        }
    };

    protected void haveDownLoad() {
        pBar.cancel();
        pBar.dismiss();
        UpdateDialog dialog = UpdateDialog.newInstance(false, "下载完成",
                "是否安装新的应用", "否", "是",
                new UpdateDialog.setOnHintListener() {
                    @Override
                    public void onNegative() {

                    }

                    @Override
                    public void onPositive() {
                        installNewApk();
                    }
                });
        dialog.show(getSupportFragmentManager(), "");
    }

    // 安装新的应用
    protected void installNewApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), appName)),
                "application/vnd.android.package-archive");
        startActivity(intent);

    }

    @Override
    protected void onResume() {
//        isForeground = true;
        super.onResume();
    }


    @Override
    protected void onPause() {
//        isForeground = false;
        super.onPause();
    }


    @Override
    protected void onDestroy() {
//        unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    public void showLoadingDialog() {
        if (loadingDialog == null && !isFinishing())
            loadingDialog = LoadingDialog.create(this).setMessage("Loading...").show();
    }

    public void hideLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }


}
